#include "stdafx.h"
#include "CEvent.h"
#include <stdio.h>
CEventManager::CEventManager(){
	_is_call_system = false;
	for(int i = 0; i< EVENT_MAX_RECORD; i++){
		_events[i]._state = EVENT_STATE_DEATH;
		_events[i]._id = 0;
		_events[i]._time = 0;
		_events[i]._data = NULL;
	}
}
CEventManager::~CEventManager(){
	for(int i = 0; i< EVENT_MAX_RECORD; i++){
		if(_events[i]._state!=EVENT_STATE_DEATH){
			if(_events[i]._data){
				delete[] _events[i]._data;
				_events[i]._data = NULL;
			}
		}
	}
}
CEvent* CEventManager::getEvents(int* pointer, unsigned int eid){
	for(int i = *pointer; i< EVENT_MAX_RECORD; i++){
		if(_events[i]._id == eid && (_events[i]._state & (EVENT_STATE_WAIT|EVENT_STATE_OUT_OF_DATE))>0){
			*pointer = i + 1;
			return &_events[i];
		}
	}
	return NULL;
}
CEvent* CEventManager::getEventOfClass(int* pointer, unsigned int classid){
	for(int i = *pointer; i< EVENT_MAX_RECORD; i++){
		if(EVENT_MACRO_ISSAMECLASS(_events[i]._id,classid) && (_events[i]._state & (EVENT_STATE_WAIT|EVENT_STATE_OUT_OF_DATE))>0){
			*pointer = i + 1;
			//printf("fount event at:%d",i);
			return &_events[i];
		}
	}
	return NULL;
}
void CEventManager::put(unsigned int id, const char* data, int len){
	for(int i = 0; i< EVENT_MAX_RECORD; i++){
		if(_events[i]._state == EVENT_STATE_DEATH){
            /*if(id == ECODE_CSOCIAL_TOURNAMENT_REWARD){
				printf("reward:%d\n",*(int*)data);
			}*/
			/*printf("put event\n");
			if(EVENT_MACRO_ISSAMECLASS(id,EVENT_CLASS_ENGINE)){
				//printf("put engine event\n");
				_is_call_system = true;
			}*/
			_is_call_system = _is_call_system | EVENT_MACRO_ISSAMECLASS(id,EVENT_CLASS_ENGINE);
			///printf("EVENT PUT:[%d at %d]\n",id,i);
			
			_events[i]._id = id;
			if(_events[i]._data != NULL){
                delete[] _events[i]._data;
                _events[i]._data = NULL;
            }
			if(len >0 && data != NULL){
				_events[i]._data = new char[len];
				MEMCOPY(data,_events[i]._data,len);
				_events[i]._data_len = len;
			}else{
				_events[i]._data = NULL;
				_events[i]._data_len = 0;
			}
			_events[i]._state = EVENT_STATE_WAIT;
			return;
		}
	}
	_error_count++;
}